package com.jyu.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jyu.reggie.common.CustomException;
import com.jyu.reggie.dto.SetmealDto;
import com.jyu.reggie.entity.Employee;
import com.jyu.reggie.entity.Setmeal;
import com.jyu.reggie.entity.SetmealDish;
import com.jyu.reggie.mapper.EmployeeMapper;
import com.jyu.reggie.mapper.SetmealMapper;
import com.jyu.reggie.service.EmployeeService;
import com.jyu.reggie.service.SetmealDishService;
import com.jyu.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;
    /**
     * @description: 新增套餐，同时保存套餐数据和 菜品关系
     * @param setmealDto
     * @return: void
     * @date: 2023/7/27 22:35
     */
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {

        this.save(setmealDto);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }

        setmealDishService.saveBatch(setmealDishes);

    }

    /**
     * @description: 删除套餐 和菜品的关联数据
     * @param ids
     * @return: void
     * @date: 2023/7/28 10:04
     */
    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus, 1);

        int count = this.count(queryWrapper);
        if (count> 0){
            throw new CustomException("套餐正在售卖中，不能删除");
        }

        this.removeByIds(ids);

        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(lambdaQueryWrapper);

    }
}
